
package com.kw.common.feign.handle;

import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.kw.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
public class BlockHandler implements UrlBlockHandler {


	@Override
	public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException {
		log.error("sentinel 降级 资源名称{}", ex.getRule().getResource(), ex);
		response.setContentType(ContentType.JSON.toString());
		response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(JSONUtil.toJsonStr(R.failed("资源访问过快")));
	}
}
